package com.raorao.rpc.properties;

import com.raorao.rpc.common.constants.LoadBalanceEnum;
import com.raorao.rpc.common.constants.ProtocolEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

import java.net.ServerSocket;

/**
 * 参数配置类，实现用户自定义参数
 *
 * @author raorao
 * @since 1.0.0
 */
@EnableConfigurationProperties(RpcProperty.class)
@ConfigurationProperties("raorao.rpc")
public class RpcProperty {

    private static Logger logger = LoggerFactory.getLogger(RpcProperty.class);

    /**
     * 默认端口
     */
    public static Integer DEFAULTPORT=27000;
    /**
     * 服务注册中心
     */
    private String registerAddress = "127.0.0.1:2181";

    /**
     * 服务端暴露端口
     */
    private Integer serverPort;

    /**
     * 服务协议（暂时只支持zookeeper）：默认走zookeeper，
     */
    private String protocol = ProtocolEnum.ZOOKEPPER.getValue();

    /**
     * 负载均很算法：默认走轮询（Round Robin）法，
     */
    private String loadBalance = LoadBalanceEnum.ROUNDROBIN.getValue();

    public String getRegisterAddress() {
        return registerAddress;
    }

    public void setRegisterAddress(String registerAddress) {
        this.registerAddress = registerAddress;
    }

    public Integer getServerPort() {
        if(this.serverPort==null){
            this.serverPort = this.getPort();
        }
        return serverPort;
    }

    public void setServerPort(Integer serverPort) {
        this.serverPort = serverPort;
    }

    public String getProtocol() {
        return protocol;
    }

    public void setProtocol(String protocol) {
        this.protocol = protocol;
    }

    public Integer getPort() {
        try{
            //读取空闲的可用端口
            ServerSocket serverSocket =  new ServerSocket(0);
            int port = serverSocket.getLocalPort();
            logger.info("【raorao-rpc】获取空闲端口："+port);
            serverSocket.close();
            return port;
        }catch (Exception ex){
            logger.error("【raorao-rpc】获取空闲端口失败："+ex.getMessage());
            return RpcProperty.DEFAULTPORT;
        }
    }

    public String getLoadBalance() {
        return loadBalance;
    }

    public void setLoadBalance(String loadBalance) {
        this.loadBalance = loadBalance;
    }
}
